//
//  UserRewardViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit

class UserRewardViewController: BaseViewController {
    var bannerView: UserRewardBannerView!
    var segmentView: UserRewardHeaderView!
    var scrollView: UIScrollView!
    
    var couponView: UserCouponView! //优惠券
    var giftView: UserGiftView! //礼品商品
    var pointView: UserPointView! //积分
    var selectIndex: NSInteger = 0 //默认优惠券

    var noticeView: GlobalNoticeView!
    var userData: UserInfoDataModel?
    var rightNaviBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("user_reward", comment: "会员奖赏")
        rightNaviBtn = UIButton()
        rightNaviBtn.frame = CGRect.init(x: kScreenWidth - 84, y: IphoneTopArea, width: 70, height: 44)
        rightNaviBtn.setup_titleLabel(text: MMLocalizedString("user_code_exchange", comment: "优惠码兑换"))
        rightNaviBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        rightNaviBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        rightNaviBtn.setTitleColor(Theme.lightNineColor, for: .highlighted)
        rightNaviBtn.addTarget(self, action: #selector(rightNaviBtnAction), for: .touchUpInside)
        self.view.addSubview(rightNaviBtn)
        
       

        noticeView = GlobalNoticeView()
        noticeView.text = ""
        self.view.addSubview(noticeView)
        
        bannerView = UserRewardBannerView(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: 100))
        self.view.addSubview(bannerView)
        
        segmentView = UserRewardHeaderView(frame: CGRect.init(x: 0, y: bannerView.frame.maxY, width: kScreenWidth, height: 92))
        segmentView.selectCallBack = {[weak self] tag in
            self?.didSelectSegmentItem(index: tag)
        }
        self.view.addSubview(segmentView)
        
        scrollView = UIScrollView.init()
        scrollView.isPagingEnabled = false
        scrollView.isScrollEnabled = false
        scrollView.contentSize = CGSize.init(width: kScreenWidth * 3, height: scrollView.frame.size.height)
        scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(scrollView)
        
        //优惠券
        couponView = UserCouponView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: scrollView.frame.size.height))
        scrollView.addSubview(couponView)
        
        //积分兑换
        giftView = UserGiftView.init(frame: CGRect.init(x: kScreenWidth, y: 0, width: kScreenWidth, height: scrollView.frame.size.height))
        giftView.exchangePointSuccessBlock = { [weak self] in
            self?.fetchGetUserInfo()
            self?.getGlobalTips()
        }
        scrollView.addSubview(giftView)
        
        //积分
        pointView = UserPointView.init(frame: CGRect.init(x: kScreenWidth * 2, y: 0, width: kScreenWidth, height: scrollView.frame.size.height))
        scrollView.addSubview(pointView)
        
        self.addSnpLayout()
        self.fetchGetUserInfo() //用户信息
        if self.selectIndex == 0 {
            self.couponView.fetchGetCouponLiset(status: "0") //优惠券
        }else{
            self.segmentView.selectIndex = 2
            self.scrollView.contentOffset = CGPoint.init(x: kScreenWidth * 2, y: 0)
            self.pointView.changePointItem()
        }
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.getGlobalTips()
        
    }
    
    private func addSnpLayout(){
        rightNaviBtn.titleLabel?.sizeToFit()
        let tempW = rightNaviBtn.titleLabel?.frame.size.width ?? 80
        rightNaviBtn.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.top.equalTo(IphoneTopArea)
            make.width.equalTo(tempW)
            make.height.equalTo(44)
        }
        
        noticeView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(NavBarHight)
            make.height.equalTo(0)
        }
        
        bannerView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(noticeView.snp.bottom)
            make.height.equalTo(100)
        }
        
        segmentView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(bannerView.snp.bottom).offset(10)
            make.height.equalTo(92)
        }
        
        scrollView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(segmentView.snp.bottom).offset(10)
            make.bottom.equalTo(0)
        }
        
        self.view.layoutIfNeeded()
        couponView.frame.size.height = scrollView.frame.size.height
        giftView.frame.size.height = scrollView.frame.size.height
        pointView.frame.size.height = scrollView.frame.size.height
    }
  
    ///顶部滚动提示
    private func getGlobalTips(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.integralProductIntegralTips, objectType: IntegralTipsResModel.self) { data in
            let resultObj = data as! IntegralTipsResModel
            if resultObj.code == "1" {
                let tips = resultObj.data?.tips ?? ""
                if tips != "" {
                    self.noticeView.text = tips
                    let hh = self.noticeView.frame.size.height
                    UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0) {
                        self.noticeView.snp.updateConstraints { make in
                            make.height.equalTo(max(44, hh))
                        }
                        self.view.layoutIfNeeded()
                    } completion: { flag in
                        self.resetChildViewLayout()
                    }
                }
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    private func resetChildViewLayout(){
        self.view.layoutIfNeeded()
        
        couponView.frame.size.height = scrollView.frame.size.height
        giftView.frame.size.height = scrollView.frame.size.height
        pointView.frame.size.height = scrollView.frame.size.height
    }
    
    ///获取用户信息
    private func fetchGetUserInfo(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberGetDetail, objectType: UserInfoResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! UserInfoResModel
            if resultObj.code == "1", let tempUserData = resultObj.data {
                self.userData = tempUserData
                self.bannerView.setUserBannerView(data: self.userData!)
                self.bannerView.snp.updateConstraints { make in
                    make.height.equalTo(100)
                }
            }else{
                //获取用户信息失败
                self.bannerView.isHidden = true
                self.bannerView.snp.updateConstraints { make in
                    make.height.equalTo(0)
                }
            }
            self.updateViewConstraints()
        } error: { err in
            self.bannerView.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            self.updateViewConstraints()
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
  
    ///切换 优惠券/礼品中心/积分
    private func didSelectSegmentItem(index: NSInteger){
        switch index {
            case 0:
                self.couponView.changeCouponItem()
            case 1:
                self.giftView.changeGifItem()
            case 2:
                self.pointView.changePointItem()
            default:
                ()
        }
        UIView.animate(withDuration: 0.2) {
            self.scrollView.contentOffset.x = kScreenWidth * CGFloat(index)
        }
    }
    
    ///优惠码兑换
    /*
    //确定使用2000积分兑换XXXX吗?
    CouponAlertView.showAlertView(title: "提示", message: "确定使用2000积分兑换XXXX吗？", cancelButtonTitle: "取消", otherButtonTitlesArr: ["确定"]) { tag, _ in

    }

    //兑换成功
    CouponAlertView.showAlertView(title: "提示", message: "兑换成功", cancelButtonTitle: "取消", otherButtonTitlesArr: ["查看"]) { tag, _ in

    }
    
    CouponAlertView.showAlertView(title: "兑换成功", message: "双11活动满1000减50", detail: "2023-1-1至2023-12-12", cancelButtonTitle: "好的") { _, _ in

    }
    
    //兑换成功标签
    CouponAlertView.showAlertView(title: "兑换成功", message: "双11活动满1000减50", detail: "2023-1-1至2023-12-12", signText: "只适用于商城产品", cancelButtonTitle: "好的") { _, _ in

    }
     */
    @objc func rightNaviBtnAction(){
        let alertView = CouponAlertView.init(
            title: MMLocalizedString("user_code_exchange", comment: "优惠码兑换"),
            cancelButtonTitle: MMLocalizedString("mainten_confirm", comment: "确定"))
        alertView.alertType = .inputAlert
        alertView.closeBtn.isHidden = false
        alertView.placeHolder = MMLocalizedString("user_please_input_coupon_code", comment: "请输入优惠码")
        alertView.clickButtonBlock = {[weak self] (tag, inputVal) in
            self?.couponView.fetchGetCouponLiset(status: "0")
        }
        alertView.show()
    }
}
